package com.ocom.security.utils;

import com.alibaba.fastjson.JSON;
import com.ocom.common.utils.ContextUtils;
import com.ocom.security.authentication.YoCiUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 权限获取工具类
 */
public class SecurityUtils {
    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     */
    public static String getUsername() {
        return getYoCiUser().getUsername();
    }



    /**
     * 获取用户
     */
    public static YoCiUser getYoCiUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof YoCiUser) {
            return (YoCiUser) principal;
        }
        return null;
    }

    /**
     * 获取用户
     */
    public static YoCiUser getYoCiUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication;
            System.out.println(auth2Authentication.getPrincipal());
            return (YoCiUser) auth2Authentication.getPrincipal();
        }

   //     System.out.println("not user");
        return null;
    }

    /**
     * 生成BCryptPasswordEncoder密码
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }


    /**
     * 获取token详情
     * @return
     */
    public static Map<String,Object> getTokenParse(){
        HttpServletRequest request= ContextUtils.getRequest();
        String token=extractToken(request);
        String jsonMap= JwtHelper.decode(token).getClaims();
        Map<String,Object> config = JSON.parseObject(jsonMap, HashMap.class);
        return config;
    }

    /**
     * 获取token详情
     * @return
     */
    public static Map<String,Object> getTokenParse(String token){
        String jsonMap= JwtHelper.decode(token).getClaims();
        Map<String,Object> config = JSON.parseObject(jsonMap, HashMap.class);
        return config;
    }

    /**
     * 获取token
     * @return
     */
    public static String getToken(){
        HttpServletRequest request= ContextUtils.getRequest();
        String token=extractToken(request);
        return token;
    }



    protected static String extractToken(HttpServletRequest request) {
        String token = extractHeaderToken(request);
        if (token == null) {
            token = request.getParameter("access_token");
            if (token != null) {
                request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, "Bearer");
            }
        }
        return token;
    }
    protected static String extractHeaderToken(HttpServletRequest request) {
        Enumeration headers = request.getHeaders("Authorization");
        String value;
        do {
            if (!headers.hasMoreElements()) {
                return null;
            }
            value = (String)headers.nextElement();
        } while(!value.toLowerCase().startsWith("Bearer".toLowerCase()));

        String authHeaderValue = value.substring("Bearer".length()).trim();
        request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, value.substring(0, "Bearer".length()).trim());
        int commaIndex = authHeaderValue.indexOf(44);
        if (commaIndex > 0) {
            authHeaderValue = authHeaderValue.substring(0, commaIndex);
        }
        return authHeaderValue;
    }

}
